package com.le.enhance.class5;

import org.junit.Test;

/**
 * 求一棵完全二叉树的节点个数，要求时间复杂度低于O(N)
 */
public class Code_06_CompleteTreeNodeNumber {

    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int data) {
            this.value = data;
        }
    }

    public static int getNum(Node head) {
        if (head == null) {
            return 0;
        }
        return process(head, 1, mostLeftLevel(head, 1));
    }

    public static int process(Node head, int level, int height) {
        if (level == height) {
            return 1;
        }
        if (mostLeftLevel(head.right, level + 1) == height) {
            return (1 << (height - 1)) + process(head.right, level + 1, height);
        } else {
            return (1 << (height - level - 1)) + process(head.left, level + 1, height);
        }
    }

    public static int mostLeftLevel(Node node, int level) {
        while (node != null) {
            level++;
            node = node.left;
        }
        return level - 1;
    }

    @Test
    public void test(){
        Node head = new Node(1);
        head.left = new Node(2);
        head.right = new Node(3);
        head.left.left = new Node(4);
        head.left.right = new Node(5);
        head.right.left = new Node(6);
        System.out.println(getNum(head));
    }


}
